﻿using AppsModel.Data_Layer.Concrete;
using AppsModel.Data_Layer.Interface;
using AppsModel.Models;
using MVC_basic.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebMatrix.WebData;

namespace AppsApi.Controllers
{
    public class WorkoutController : ApiController
    {
        private readonly IdbWorkout db;
        public WorkoutController(IdbWorkout IdbW)
        {
            db = IdbW;
            WebSecurity_Singleton.init();
        }
        public List<Workout> Get()
        {
            List<Workout> workouts = db.getWorkouts();
            return workouts;
        }

        public Workout Get(int id)
        {
            Workout workout = db.getWorkout(id, false);
            return workout;
        }

        public HttpResponseMessage PostWorkout(Workout workout)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            workout = db.addWorkout(workout.name, workout.categoryId, workout.additionalFields ?? null, id);
            var response = Request.CreateResponse<Workout>(HttpStatusCode.Created, workout);

            string uri = Url.Link("DefaultApi", new { id = workout.id });
            return response;
        }

        public HttpResponseMessage DeleteWorkout(string id)
        {
            int Wid = Convert.ToInt32(id);
            Workout workout = db.getWorkout(Wid, true);
            int userId = WebSecurity.GetUserId(User.Identity.Name);
            if (workout == null || userId != workout.userId || !WebSecurity.IsAuthenticated)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            db.deleteWorkout(Wid);
            var response = Request.CreateResponse<Workout>(HttpStatusCode.OK, workout);
            return response;
        }

        public HttpResponseMessage PutWorkout(int id, Workout workout)
        {
            int userId = WebSecurity.GetUserId(User.Identity.Name);
            if (workout == null || userId != workout.userId || !WebSecurity.IsAuthenticated)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            workout = db.updateWorkout(workout.id, workout.name, workout.categoryId, workout.additionalFields ?? null, id);
            var response = Request.CreateResponse<Workout>(HttpStatusCode.OK, workout);

            string uri = Url.Link("DefaultApi", new { id = workout.id });
            return response;
        }
    }
}
